<?php

namespace Question\Service;

/**
 * 题目业务
 */
class Question {
	private $_daoQuestionModel;
	private $_daoDeviceModel;

	const RELOAD_QUESTION_SET_ID = 1;


	/**
	 * 构造函数
	 */
	public function __construct() {
		$this->_daoQuestionModel = \Lsf\Loader::Model('DaoQuestion', TRUE);
		$this->_daoDeviceModel = \Lsf\Loader::Model('DaoDevice', TRUE);
	}

	/**
	 * 题目列表
	 */
	public function getQuestionListWX($questionSetId){
		$r = rand(1, 2);
		$where = [
			'set_id' => $r,
//			'question_id' => ['gt', $id],
			'status' => 1,
		];
		$list = $this->_daoQuestionModel->select('*', $where, 'question_id ASC', 10, FALSE);
		foreach ($list as &$item){
			$choiceStr = $item['choice_info'];
			$choice = json_decode($choiceStr, TRUE);
			if(json_last_error() > 0){
				\Lsf\Loader::plugin('Log')->error(JSON_FAIL, ['desc' => 'choice_info json error', 'choice' => $item]);
				return FALSE;
			}
			$item['choice_info'] = $choice;
			continue;
		}
		return [
			'question_set_id' => $r,
			'list' => $list,
			'page_no' => 1,
			'page_size' => 10,
			'total_page' => 1,
			'total_num' => 10,
		];
	}


	/**
	 * 题目列表
	 */
	public function getQuestionListPage($questionSetId, $pageSize = 10, $pageNo = 1){
		$where = [
			'set_id' => $questionSetId,
			'status' => 1,
		];
		$limit = ($pageNo - 1) * $pageSize;
		$list = $this->_daoQuestionModel->select('*', $where, 'question_id DESC', $limit . ',' . $pageSize, FALSE);
		foreach ($list as &$item){
			$choiceStr = $item['choice_info'];
			$choice = json_decode($choiceStr, TRUE);
			if(json_last_error() > 0){
				\Lsf\Loader::plugin('Log')->error(JSON_FAIL, ['desc' => 'choice_info json error', 'choice' => $item]);
				return FALSE;
			}
			$item['choice_info'] = $choice;
			continue;
		}
		$count = $this->_daoQuestionModel->count('question_id', $where);
		if(!is_int($count)){
			return FALSE;
		}
		$totalPage = intval($count / $pageSize);
		if($count % $pageSize > 0){
			$totalPage++;
		}
		return [
			'question_set_id' => $questionSetId,
			'list' => $list,
			'page_no' => intval($pageNo),
			'page_size' => intval($pageSize),
			'total_page' => $totalPage,
			'total_num' => $count,
		];
	}

	/**
	 * 添加题目
	 */
	public function addQuestion($questionSetId, $questionInfo, $answer, $choiceInfo){
		$choiceInfoStr = json_encode($choiceInfo, JSON_UNESCAPED_UNICODE);
		if(json_last_error() > 0){
			\Lsf\Loader::plugin('Log')->error(8000001, ['data' => $choiceInfo]);
			return FALSE;
		}
		// 插入数据
		$question = [
			'set_id' 			=> $questionSetId,
			'question_desc' 	=> $questionInfo,
			'choice_info'    	=> $choiceInfoStr,
			'answer' 			=> $answer,
			'type' 				=> 1,
			'status' 			=> 1,
			'create_time' 		=> date("Y-m-d H:i:s",time())
 		];
		$id = $this->_daoQuestionModel->insert($question);
		if ($id === FALSE) {
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_question',
				'insert'     => $question
			]);
			return FALSE;
		}
		return ['question_id' => $id];
	}

	/**
	 * 删除题目
	 */
	public function delQuestion($questionId){
		// 更新数据
		$question = [
			'status' => 2,
		];
		$where = [
			'question_id' => $questionId
		];
		$row = $this->_daoQuestionModel->update($question, $where);
		if ($row === FALSE) {
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_question',
				'question' => $question,
				'where' =>  $where
			]);
			return FALSE;
		}
		return ['question_id' => $questionId];
	}

	/**
	 * 修改题目
	 */
	public function editQuestion($questionId, $questionInfo, $answer, $choiceInfo){
		$choiceInfoStr = json_encode($choiceInfo, JSON_UNESCAPED_UNICODE);
		if(json_last_error() > 0){
			\Lsf\Loader::plugin('Log')->error(8000001, ['data' => $choiceInfo]);
			return FALSE;
		}
		// 修改数据
		$question = [
			'question_desc' => $questionInfo,
			'choice_info' 	=> $choiceInfoStr,
			'answer' 	    => $answer,
		];
		$where = [
			'question_id' => $questionId
		];
		$row = $this->_daoQuestionModel->update($question, $where);
		if ($row !== 1) {
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_question',
				'insert'     => $question
			]);
			return FALSE;
		}
		return ['question_id' => $questionId];
	}

	/**
	 * 轮询题目状况
	 */
	public function reloading($deviceId){
		// 获取主持人设备状态
		$where = [
			'group_id' => 3,
			'status' => 1,
		];
		$device = $this->_daoDeviceModel->select('id,device_id,group_id,center_question_id,is_show,set_id', $where, 'update_time DESC', 1, FALSE);
		// 未设置主持人机器
		if(empty($device)){
			return -1;
		}
		// 没有设置题目套，则随机生成
		if(empty($device[0]['set_id'])){
			$setId = rand(1,2);
			// 生成后写入主持人设备
			$up = [
				'set_id' => $setId
			];
			$where = [
				'device_id' => $device[0]['device_id'],
			];
			$this->_daoDeviceModel->update($up, $where);
		}else{
			$setId = $device[0]['set_id'];
		}
		// 获取题目信息
		$question = [];
		$questionId = $device[0]['center_question_id'];
		if($questionId > 0) {
			$where2 = ['question_id' => $questionId];
			$question = $this->_daoQuestionModel->select('*', $where2, 'question_id ASC', 1, FALSE);
		}
		if($questionId == 0){
			$where2 = ['status' => 1, 'set_id' => $setId];
			$question = $this->_daoQuestionModel->select('*', $where2, 'question_id ASC', 1, FALSE);
		}
		// 获取轮询设备状态
		$where = [
			'device_id' => $deviceId,
		];
		$thisDevice = $this->_daoDeviceModel->select('id,device_id,group_id', $where, 'id DESC', 1, FALSE);
		// 组别信息
		switch ($thisDevice[0]['group_id']){
		case 1:
			{
				$result['group_name'] = 'A组';
				break;
			}
		case 2:
			{
				$result['group_name'] = 'B组';
				break;
			}
		case 3:
			{
				$result['group_name'] = '主持人';
				break;
			}
		default:
			{
				$result['group_name'] = '未知';
				break;
			}
		}
		$result['group_id'] = $thisDevice[0]['group_id'];
		$question[0]['choice_info'] = json_decode($question[0]['choice_info']);
		if(json_last_error() > 0){
			\Lsf\Loader::plugin('Log')->error(JSON_FAIL, ['desc' => 'choice_info json error', 'choice' => $question[0]]);
			return FALSE;
		}
		$questionNo = $question[0]['question_id'] % 10;
		if($questionNo == 0){
			$questionNo = 10;
		}
		$question[0]['question_desc'] = $questionNo . '.' . $question[0]['question_desc'];
		$result['is_show_answer'] = $device[0]['is_show'] === 1;
		$result['question'] = $question[0];
		return $result;
	}

	/**
	 * 主持人操作
	 */
	public function operate($deviceId, $operateType, $questionId){
		$owerDevice = $this->_daoDeviceModel->select('id,device_id,group_id,center_question_id,is_show,set_id', ['device_id' => $deviceId], 'update_time DESC', 1, FALSE);
		$setId = $owerDevice[0]['set_id'];
		switch ($operateType){
			//上一题
		case 1:
			{
				// 查询题目
				if($questionId == 0){
					$where2 = ['status' => 1, 'set_id' => $setId];
					$question = $this->_daoQuestionModel->select('*', $where2, 'question_id ASC', 1, FALSE);
					$result = [
						'question_info' => $question[0]
					];
					$result['question_info']['choice_info'] = json_decode($result['question_info']['choice_info']);
					if(json_last_error() > 0){
						\Lsf\Loader::plugin('Log')->error(JSON_FAIL, ['desc' => 'choice_info json error', 'choice' => $result['question_info']]);
						return FALSE;
					}
					$questionNo = $result['question_info']['question_id'] % 10;
					if($questionNo == 0){
						$questionNo = 10;
					}
					$result['question_info']['question_desc'] = $questionNo . '.' . $result['question_info']['question_desc'];
					return $result;
					break;
				}
				$where = [
					'set_id' => $setId,
					'question_id' => ['lt', $questionId],
				];
				$list = $this->_daoQuestionModel->select('*', $where, 'question_id DESC', 1, FALSE);
				if(empty($list)){
					// 第一题
					$list = [[]];
					return $list;
				}else {
					// 更新设备
					$deviceUp = [
						'is_show'            => 0,
						'center_question_id' => $list[0]['question_id'],
						'update_time'        => date("Y-m-d H:i:s", time()),
						'rush_user_answer' => '',
						'rush_start_flag' => 2

					];
					$where = [
						'device_id' => $deviceId
					];
					$row = $this->_daoDeviceModel->update($deviceUp, $where);
					if ($row !== 1) {
						\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
							'model_name' => 'dao_device',
							'device'     => $deviceUp,
							'where'      => $where
						]);
						return FALSE;
						break;
					}
				}
				$result = [
					'question_info' => $list[0]
				];
				$result['question_info']['choice_info'] = json_decode($result['question_info']['choice_info']);
				if(json_last_error() > 0){
					\Lsf\Loader::plugin('Log')->error(JSON_FAIL, ['desc' => 'choice_info json error', 'choice' => $result['question_info']]);
					return FALSE;
				}
				$questionNo = $result['question_info']['question_id'] % 10;
				if($questionNo == 0){
					$questionNo = 10;
				}
				$result['question_info']['question_desc'] = $questionNo . '.' . $result['question_info']['question_desc'];
				return $result;
				break;
			}
			//下一题
		case 2:
			{
				// 查询题目
				if($questionId == 0){
					$where2 = ['status' => 1, 'set_id' => $setId];
					$question = $this->_daoQuestionModel->select('*', $where2, 'question_id ASC', 1, FALSE);
					$result = [
						'question_info' => $question[0]
					];
					$result['question_info']['choice_info'] = json_decode($result['question_info']['choice_info']);
					if(json_last_error() > 0){
						\Lsf\Loader::plugin('Log')->error(JSON_FAIL, ['desc' => 'choice_info json error', 'choice' => $result['question_info']]);
						return FALSE;
					}
					$questionNo = $result['question_info']['question_id'] % 10;
					if($questionNo == 0){
						$questionNo = 10;
					}
					$result['question_info']['question_desc'] = $questionNo . '.' . $result['question_info']['question_desc'];
					return $result;
					break;
				}
				$where = [
					'set_id' => $setId,
					'question_id' => ['gt', $questionId],
				];
				$list = $this->_daoQuestionModel->select('*', $where, 'question_id ASC', 1, FALSE);
				if(empty($list)){
					// 最后一题
					$list = [[]];
					return $list;
				}else {
					// 更新设备
					$deviceUp = [
						'is_show'            => 0,
						'center_question_id' => $list[0]['question_id'],
						'update_time'        => date("Y-m-d H:i:s", time()),
						'rush_user_answer' => '',
						'rush_start_flag' => 2

					];
					$where = [
						'device_id' => $deviceId
					];
					$row = $this->_daoDeviceModel->update($deviceUp, $where);
					if ($row !== 1) {
						\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
							'model_name' => 'dao_device',
							'device'     => $deviceUp,
							'where'      => $where
						]);
						return FALSE;
						break;
					}
				}
				$result = [
					'question_info' => $list[0]
				];
				$result['question_info']['choice_info'] = json_decode($result['question_info']['choice_info']);
				if(json_last_error() > 0){
					\Lsf\Loader::plugin('Log')->error(JSON_FAIL, ['desc' => 'choice_info json error', 'choice' => $result['question_info']]);
					return FALSE;
				}
				$questionNo = $result['question_info']['question_id'] % 10;
				if($questionNo == 0){
					$questionNo = 10;
				}
				$result['question_info']['question_desc'] = $questionNo . '.' . $result['question_info']['question_desc'];
				return $result;
				break;
			}
			// 显示答案
		case 3:
			{
				// 更新设备
				$deviceUp = [
					'is_show'      => 1,
					'update_time'  => date("Y-m-d H:i:s", time())
				];
				$where = [
					'device_id' => $deviceId
				];
				$row = $this->_daoDeviceModel->update($deviceUp, $where);
				if ($row !== 1) {
					\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
						'model_name' => 'dao_device',
						'device'     => $deviceUp,
						'where'      => $where
					]);
					return FALSE;
				}
				return [];
				break;
			}
		default:
			{
				return FALSE;
			}

		}
	}

}